package Game;

import AI.AI;
import View.BoardPanel;
import View.MainPanel;
import AI.CEvaluate;
import java.util.*;

public class GameController {
	private boolean firstTurn = true;
	private Player[] playerArr;
	private MainPanel mp;
	private Pieces pieces;
	private Rule rule;
	private BoardPanel bPanel;
	private int turnColor;
	private Stack<OneStep> stack;
	public int step;

	public GameController(MainPanel mp) {
		this.mp = mp;
		pieces = mp.p;
		bPanel = mp.bPanel;
		rule = new Rule(pieces);
		stack=new Stack<OneStep>();
	}

	public void start() {
		stack.clear();
		step = 0;
		turnColor = Pieces.BLACK;
		int deep = Integer.parseInt(mp.deepField.getText());
		int aic, aiopc;
		firstTurn = mp.firstTurn;
		if (firstTurn) {
			aic = Pieces.WHITE;
			aiopc = Pieces.BLACK;
		} else {
			aic = Pieces.BLACK;
			aiopc = Pieces.WHITE;
		}
		Robot r = new Robot(aic, aiopc, deep, pieces.getPieces(), this);
		Human h = new Human(aiopc, this);
		MouseAction mAction = new MouseAction(pieces, mp.bPanel, h);
		playerArr = new Player[] { r, h };
		pieces.init();
		bPanel.init();
		bPanel.repaint();
		bPanel.addMouseListener(mAction);
		for (int i = 0; i < 2; i++) {
			playerArr[i].notifyPlayer(turnColor);
		}
	}

	public void notifyController(Player p) {
		int color = p.getColor();
		System.out.println(color);
		OneStep oneStep = p.getNextStep();
		stack.push(oneStep);
		int ix = oneStep.x;
		int iy = oneStep.y;
		if (pieces.getOnePiece(ix, iy) == Pieces.BLANK) {
			pieces.setOnePiece(ix, iy);
			bPanel.paintImmediately(bPanel.getX(), bPanel.getY(), bPanel
					.getWidth(), bPanel.getHeight());
			if (rule.isWin()) {
				bPanel.hasWon = true;
				for(int i=0;i<2;i++) {
					playerArr[i].setGameOver();
				}
			} else {
				firstTurn = !firstTurn;
				turnColor = turnColor == Pieces.BLACK ? Pieces.WHITE
						: Pieces.BLACK;
				step++;
				for (int i = 0; i < 2; i++) {
					playerArr[i].notifyPlayer(turnColor);
				}
			}

			bPanel.repaint();
		}
	}
	
	public void undo() {
		if(stack.size()<3) {
			return;
		}
		step-=2;
		OneStep step=stack.pop();
		pieces.removeOnePiece(step.x, step.y);
		step=stack.pop();
		pieces.removeOnePiece(step.x, step.y);
		step=stack.peek();
		pieces.lastX=step.x;
		pieces.lastY=step.y;
		bPanel.repaint();
	}
}
